const app = getApp()

Page({
  data: {
    activeTab: 0,
    tabs: [
      { title: '商品管理', icon: 'goods' },
      { title: '店铺管理', icon: 'shop' },
      { title: '订单管理', icon: 'order' }
    ],
    products: [],
    shops: [],
    orders: [],
    orderStatus: ['全部', '待付款', '已付款', '已完成', '已取消'],
    currentStatus: 0,
    orderStatusMap: {
      unpaid: '待付款',
      processing: '已付款',
      completed: '已完成',
      cancelled: '已取消'
    }
  },

  onLoad: function() {
    this.checkAdminAuth()
    this.loadProducts()
  },

  // 检查管理员权限
  async checkAdminAuth() {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('users').where({
        _openid: app.globalData.openid
      }).get()
      
      if (!data[0] || data[0].role !== 'admin') {
        wx.showToast({
          title: '无管理员权限',
          icon: 'none'
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          })
        }, 1500)
      }
    } catch (error) {
      console.error('检查管理员权限失败：', error)
    }
  },

  // 切换标签页
  switchTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ activeTab: index })
    
    switch(index) {
      case 0:
        this.loadProducts()
        break
      case 1:
        this.loadShops()
        break
      case 2:
        this.loadOrders()
        break
    }
  },

  // 加载商品列表
  async loadProducts() {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('products')
        .orderBy('createTime', 'desc')
        .get()
      
      this.setData({ products: data })
    } catch (error) {
      console.error('加载商品列表失败：', error)
    }
  },

  // 添加商品
  addProduct() {
    wx.navigateTo({
      url: '/pages/admin/product/edit'
    })
  },

  // 编辑商品
  editProduct(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/product/edit?id=${id}`
    })
  },

  // 删除商品
  async deleteProduct(e) {
    const id = e.currentTarget.dataset.id
    try {
      await wx.showModal({
        title: '确认删除',
        content: '确定要删除这个商品吗？'
      })
      
      const db = wx.cloud.database()
      await db.collection('products').doc(id).remove()
      
      wx.showToast({
        title: '删除成功'
      })
      
      this.loadProducts()
    } catch (error) {
      console.error('删除商品失败：', error)
    }
  },

  // 加载店铺列表
  async loadShops() {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('shops')
        .orderBy('createTime', 'desc')
        .get()
      
      this.setData({ shops: data })
    } catch (error) {
      console.error('加载店铺列表失败：', error)
    }
  },

  // 添加店铺
  addShop() {
    wx.navigateTo({
      url: '/pages/admin/shop/edit'
    })
  },

  // 编辑店铺
  editShop(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/shop/edit?id=${id}`
    })
  },

  // 删除店铺
  async deleteShop(e) {
    const id = e.currentTarget.dataset.id
    try {
      await wx.showModal({
        title: '确认删除',
        content: '确定要删除这个店铺吗？'
      })
      
      const db = wx.cloud.database()
      await db.collection('shops').doc(id).remove()
      
      wx.showToast({
        title: '删除成功'
      })
      
      this.loadShops()
    } catch (error) {
      console.error('删除店铺失败：', error)
    }
  },

  // 加载订单列表
  async loadOrders() {
    try {
      const db = wx.cloud.database()
      let query = db.collection('orders')
        .orderBy('createTime', 'desc')
      
      // 根据状态筛选
      if (this.data.currentStatus > 0) {
        const status = ['pending', 'processing', 'completed', 'cancelled'][this.data.currentStatus - 1]
        query = query.where({
          status: status
        })
      }
      
      const { data } = await query.get()
      this.setData({ orders: data })
    } catch (error) {
      console.error('加载订单列表失败：', error)
    }
  },

  // 切换订单状态
  onStatusChange(e) {
    this.setData({
      currentStatus: parseInt(e.detail.value)
    })
    this.loadOrders()
  },

  // 接受订单
  async acceptOrder(e) {
    const id = e.currentTarget.dataset.id
    try {
      await wx.showModal({
        title: '确认接单',
        content: '确定接受这个订单吗？'
      })
      
      const db = wx.cloud.database()
      await db.collection('orders').doc(id).update({
        data: {
          status: 'processing',
          updateTime: db.serverDate()
        }
      })
      
      wx.showToast({
        title: '已接单'
      })
      
      this.loadOrders()
    } catch (error) {
      console.error('接单失败：', error)
    }
  },

  // 完成订单
  async completeOrder(e) {
    const id = e.currentTarget.dataset.id
    try {
      await wx.showModal({
        title: '确认完成',
        content: '确定完成这个订单吗？'
      })
      
      const db = wx.cloud.database()
      await db.collection('orders').doc(id).update({
        data: {
          status: 'completed',
          updateTime: db.serverDate()
        }
      })
      
      wx.showToast({
        title: '已完成'
      })
      
      this.loadOrders()
    } catch (error) {
      console.error('完成订单失败：', error)
    }
  },

  // 拒绝订单
  async rejectOrder(e) {
    const id = e.currentTarget.dataset.id
    try {
      const { confirm, content } = await wx.showModal({
        title: '拒绝订单',
        content: '确定要拒绝这个订单吗？',
        editable: true,
        placeholderText: '请输入拒绝原因'
      })
      
      if (confirm) {
        const db = wx.cloud.database()
        await db.collection('orders').doc(id).update({
          data: {
            status: 'cancelled',
            cancelReason: content,
            updateTime: db.serverDate()
          }
        })
        
        wx.showToast({
          title: '已拒绝'
        })
        
        this.loadOrders()
      }
    } catch (error) {
      console.error('拒绝订单失败：', error)
    }
  }
}) 